import { Component, OnInit } from '@angular/core';
import { TOKEN, USERINFO } from '../service/constant';
import { UtilsService } from '../service/utils.service';
import { Router } from '@angular/router';
import { LoadingController } from '@ionic/angular';
import { RequestService } from '../service/request/request.service';

interface FROM {
  username: string;
  password: string;
}
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  from: FROM = {
    username: '',
    password: '',
  };
  constructor(
    private utils: UtilsService,
    private router: Router,
    private http: RequestService,
    private loading: LoadingController,
  ) {}

  ngOnInit() {}
  // 密码变化
  ChangePass(val) {
    const data = val.detail.value;
    this.from.password = data;
  }
  // 用户名变化
  ChangeUser(val) {
    const data = val.detail.value;
    this.from.username = data;
  }
  // 登录
  async Submit() {
    if (this.from.username && this.from.password) {
      const params = {
        username: this.from.username,
        password: this.from.password,
      };
      const loading = await this.loading.create({
        message: '登录中...',
        backdropDismiss: false,
      });
      await loading.present();
      this.http.post('sys/mLogin', params).subscribe((res) => {
        console.log(res, 'res');
        if (res && res.code === 200) {
          const data = res.result.userInfo;
          loading.dismiss();
          localStorage.setItem(TOKEN, res.result.token);
          localStorage.setItem(USERINFO, JSON.stringify(data));
          this.utils.showToast('登录成功!', 'top');
          this.router.navigate(['']);
        } else {
          loading.dismiss();
          this.utils.showToast(res.message, 'top');
        }
      });
      // localStorage.setItem(TOKEN, '123');
    } else {
      this.utils.showToast('请输入用户名或者密码!', 'top');
    }
  }
}
